package com.audaque.springboot.foshanupload.security.valid.rsp.kid;

import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import com.audaque.springboot.foshanupload.core.result.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@Component
public class SessionInformationExpiredHandler implements SessionInformationExpiredStrategy {

    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent sessionInformationExpiredEvent) throws IOException, ServletException {
        HttpServletRequest request = sessionInformationExpiredEvent.getRequest();
        HttpServletResponse response = sessionInformationExpiredEvent.getResponse();
        String url = request.getRequestURL().toString();
        log.debug("url："+url);

        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();



        R r = new R<>();
        r.setSuccess(false);
        r.setStatus(ResultCodeEnum.SESSION_KIDOUT.getStatus());
        r.setDescription(ResultCodeEnum.SESSION_KIDOUT.getDescription());

        try {
            out.write(objectMapper.writeValueAsString(r));
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }


    }
}